<?php
/**
 * Created by laoyu.
 * User: hilaoyu@qq.com
 * Date: 2018/5/8
 * Time: 16:32
 */

namespace  Hilaoyu\LaravelExtend\Services\Variables;


use Hilaoyu\LaravelExtend\Entity;

abstract class VariablesEntityAbstract extends Entity
{
    protected static $_variables_cache=[];
    protected function alterDeleteBeforeTrans($model,$force=false)
    {
        if($model && $model->required){
            $this->setError('此项为系统必须，不可删除');
            return null;
        }
        $model = parent::alterDeleteBeforeTrans($model,$force);



        return $model;
    }

    static public function get($key,$default=null){

        $key = trim($key);
        if(!array_key_exists($key,static::$_variables_cache)){
            $_this = new static();

            $model =  $_this->find(function ($query) use ($key){
                return $query->where('key','=',$key) ;
            });

            static::$_variables_cache[$key] =  data_get($model,'value',$default);
        }
        return data_get(static::$_variables_cache,$key,$default);

    }


    static public function set($key,$value,$name='',$remark=''){

        $key = trim($key);
        $name = trim($name);

        $_this = new static();

        $model =  $_this->find(function ($query) use ($key){
            return $query->where('key','=',$key) ;
        });

        $data = [
            'key' => $key,
            'value' => $value,
            'name' => $name,
            'remark' => $remark,
        ];



        if(!$_this->save($data,$model)){
            static::setStaticError($_this->getError());
            return false;
        }
        static::$_variables_cache[$key] = $value;
        return true;
    }

}
